package logic

import (
	"context"
	"encoding/json"
	"house/models/cache"
	"house/models/mysql"
	"time"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListHouseLogic {
	return &ListHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListHouseLogic) ListHouse(in *houserpc.ListHouseRequest) (*houserpc.ListHouseResponse, error) {
	// todo: add your logic here and delete this line

	var houses []mysql.House
	cacheData, _ := cache.Rdb.Get(cache.Ctx, "ListHouse").Result()
	if cacheData == "" {
		mysql.DB.Find(&houses)
		jsonData, _ := json.Marshal(houses)
		cache.Rdb.Set(cache.Ctx, "ListHouse", jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &houses)
	}

	var listHouse []*houserpc.ListHouse

	for _, house := range houses {
		list := houserpc.ListHouse{
			Titls: house.Title,
			Types: house.Types,
			Ads:   house.Ads,
			Price: float32(house.Price),
		}
		listHouse = append(listHouse, &list)
	}
	return &houserpc.ListHouseResponse{
		List: listHouse,
	}, nil
}
